package logic

import (
	"context"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentBindWechatLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAgentBindWechatLogic(ctx context.Context, svcCtx *svc.ServiceContext) AgentBindWechatLogic {
	return AgentBindWechatLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentBindWechatLogic) AgentBindWechat(req *types.AgentBindWechatReq) error {
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return err
	}
	agentParam, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: uid})
	if err != nil {
		return errorx.NewMsgCodeError(errorx.UnLoginCode, "请重新登录")
	}

	auth := l.svcCtx.WxMiniProgram.GetAuth()
	result, err := auth.Code2Session(req.JsCode)
	if err != nil || result.ErrCode != 0 || result.OpenID == "" {
		return errorx.NewReasonError("微信授权失败", err.Error())
	}
	logx.Infof("微信登陆：%v", result)

	// 当前微信未绑定账号、支付时，绑定openID ，unionId不绑定，作为唯一微信登陆
	agentParam.OpenId = result.OpenID
	_, err = l.svcCtx.AgentRpc.AgentUpdate(l.ctx, agentParam)
	if err != nil {
		return err
	}
	return nil
}
